﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace RbacSystem.Controllers
{
    [Route("/[controller]/[action]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        private readonly IWebHostEnvironment environment;
        private readonly IConfiguration configuration;

        /// <summary>
        /// 构造函数注入
        /// </summary>
        /// <param name="environment"></param>
        public UploadController(IWebHostEnvironment environment, IConfiguration configuration)
        {
            this.environment = environment;
            this.configuration = configuration;
        }

        /// <summary>
        /// web项目  
        /// web根  wwwroot E:\Tech\RbacSystem\RbacSystem\wwwroot\
        /// 内容根   E:\Tech\RbacSystem\RbacSystem
        /// 注入---服务
        /// </summary>
        /// <param name="formFile"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UploadFile(IFormFile formFile)
        {
            if(formFile.Length / 1000 > 200)
            {
                return Ok(new
                {
                    Msg = "超过最大文件大小"
                });
            }

            //1、获取配置文件允许类型
            var filetype = configuration["AllowFileType"].Split(',');

            //3、根据当前文件类型判断            
            if (!filetype.Any(m => m.ToLower() == Path.GetExtension(formFile.FileName).ToLower()))
            {
                throw new Exception("文件类型不正确");
            }


            var DirPath = $"/UploadFile/{DateTime.Now.ToString("yyyyMM")}/{DateTime.Now.ToString("yyyyMMdd")}";

            Directory.CreateDirectory($"{environment.WebRootPath}{DirPath}");

            var FilePath = $"{DirPath}/{DateTime.Now.ToString("yyyyMMddHHmmss")}{Path.GetExtension(formFile.FileName)}";
            
            //释放非托管资源
            using (FileStream file = new FileStream($"{environment.WebRootPath}/{FilePath}", FileMode.Create))
            {
                formFile.CopyTo(file);
            }

            return Ok(new {
                FilePath = FilePath
            });
        }

        [HttpPost("/UploadFiles")]
        public async Task<IActionResult> UploadFileAsync(IFormFile formFile)
        {
            if (formFile.Length / 1000 > 200)
            {
                return Ok(new
                {
                    Msg = "超过最大文件大小"
                });
            }

            //1、获取配置文件允许类型
            var filetype = configuration["AllowFileType"].Split(',');

            //3、根据当前文件类型判断            
            if (!filetype.Any(m => m.ToLower() == Path.GetExtension(formFile.FileName).ToLower()))
            {
                throw new Exception("文件类型不正确");
            }


            var DirPath = $"/UploadFile/{DateTime.Now.ToString("yyyyMM")}/{DateTime.Now.ToString("yyyyMMdd")}";

            Directory.CreateDirectory($"{environment.WebRootPath}{DirPath}");

            var FilePath = $"{DirPath}/{DateTime.Now.ToString("yyyyMMddHHmmss")}{Path.GetExtension(formFile.FileName)}";

            //释放非托管资源
            using (FileStream file = new FileStream($"{environment.WebRootPath}/{FilePath}", FileMode.Create))
            {
                await formFile.CopyToAsync(file);
            }

            return Ok(new
            {
                FilePath = FilePath
            });

            
        }
    }
}
